package hu.stud.uszeged.inf.prf.prftrac.session.controllers;

import hu.stud.uszeged.inf.prf.prftrac.entity.Milestone;
import hu.stud.uszeged.inf.prf.prftrac.entity.Ticket;
import hu.stud.uszeged.inf.prf.prftrac.session.EventHome;
import hu.stud.uszeged.inf.prf.prftrac.session.TicketHome;
import hu.stud.uszeged.inf.prf.prftrac.session.dao.TicketDao;
import hu.stud.uszeged.inf.prf.prftrac.session.dao.UserDao;
import hu.stud.uszeged.inf.prf.prftrac.session.enums.EntityType;
import hu.stud.uszeged.inf.prf.prftrac.session.enums.EventType;

import java.util.Date;
import java.util.List;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.security.Credentials;

@Scope(ScopeType.EVENT)
@Name("ticketsController")
public class TicketsController {
	
	@In("#{credentials}")
	private Credentials creds;
	@In("#{eventHome}")
	private EventHome eventHome;
	@In("#{userDao}")
	private UserDao userDao;
	@In("#{ticketDao}")
	private TicketDao ticketDao;
	@In("#{ticketHome}")
	private TicketHome ticketHome;
	
	public List<Ticket> ticketListByMilestone(Milestone milestone) {
		return ticketDao.getTickets(milestone);
	}
	
	public String persist() {
		String result = ticketHome.persist();
		if (result.equals("persisted")) {
			eventHome.getInstance().setDateTime(new Date());
			eventHome.getInstance().setUser(userDao.getUserByNickName(creds.getUsername()));
			eventHome.getInstance().setType(EventType.NEW_TICKET);
			eventHome.getInstance().setEntityType(EntityType.TICKET);
			eventHome.getInstance().setEntityId(ticketHome.getInstance().getId());
			eventHome.persist();
		}
		return result;
	}
	
	public String update() {
		String result = ticketHome.update();
		if (result.equals("updated")) {
			eventHome.getInstance().setDateTime(new Date());
			eventHome.getInstance().setUser(userDao.getUserByNickName(creds.getUsername()));
			eventHome.getInstance().setType(EventType.UPDATE_TICKET);
			eventHome.getInstance().setEntityType(EntityType.TICKET);
			eventHome.getInstance().setEntityId(ticketHome.getInstance().getId());
			eventHome.persist();
		}
		return result;
	}
	
	public String remove() {
		String result = ticketHome.remove();
		if (result.equals("removed")) {
			eventHome.getInstance().setDateTime(new Date());
			eventHome.getInstance().setUser(userDao.getUserByNickName(creds.getUsername()));
			eventHome.getInstance().setType(EventType.DELETE_TICKET);
			eventHome.getInstance().setEntityType(EntityType.TICKET);
			eventHome.getInstance().setEntityId(ticketHome.getInstance().getId());
			eventHome.persist();
		}
		return result;
	}
}
